package com.hanfb.mall.inventory.service.impl;

import com.hanfb.mall.inventory.dao.RedisDao;
import com.hanfb.mall.inventory.mapper.ProductInventoryMapper;
import com.hanfb.mall.inventory.model.ProductInventory;
import com.hanfb.mall.inventory.service.ProductInventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @作者： Hanfb
 * @描述：
 * @时间： 2020年10月11日
 */
@Service
public class ProductInventoryImpl implements ProductInventoryService {

    @Resource
    ProductInventoryMapper mapper;

    @Resource
    RedisDao redisDao;

    @Override
    public void updateProductInventroy(ProductInventory productInventory) {
        mapper.updateProductInventroy(productInventory);
        System.out.println("===========日志============：已修改数据库中的库存，商品id="+productInventory.getProductId()+", 商品数量cnt="+productInventory.getInventoryCnt());
    }

    @Override
    public void removeProductInventroyCache(ProductInventory productInventory) {
        String key="product:inventory:"+productInventory.getProductId();
        redisDao.deleteKey(key);
        System.out.println("===========日志============：删除redis中的缓存，key="+key);
    }

    @Override
    public ProductInventory findProductInventory(Integer productId) {
        return mapper.findProductInventory(productId);
    }

    @Override
    public void setProductInventoryCache(ProductInventory productInventory) {
        String key="product:inventory:"+productInventory.getProductId();
        redisDao.set(key,String.valueOf(productInventory.getInventoryCnt()));
        System.out.println("===========日志============：已更新商品库存的缓存，商品id="+productInventory.getProductId()+",商品库存数量cnt="+productInventory.getInventoryCnt()+".key"+key);
    }

    @Override
    public ProductInventory getProductInventoryCache(Integer productId) {
        Long inventoryCnt=0L;
        String key="product:inventory:"+productId;

        String result= redisDao.get(key);

        if(!StringUtils.isEmpty(result)){

            try {
                inventoryCnt=Long.valueOf(result);
                return new ProductInventory(productId,inventoryCnt);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

        }
       return null;
    }
}
